package com.zhongjian.technologycal.mall.activity.personal;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.personal.activity.ChangePasswordActivity;
import com.zhongjian.technologycal.mall.activity.personal.activity.NewsAddressListActivity;
import com.zhongjian.technologycal.mall.activity.personal.activity.NewsAddressListManageActivity;
import com.zhongjian.technologycal.mall.activity.personal.activity.SettingPasswordActivity;
import com.zhongjian.technologycal.mall.activity.personal.activity.SettingPayPasswordActivity;
import com.zhongjian.technologycal.mall.activity.web.WebViewMarkActivity;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.LoginBean;
import com.zhongjian.technologycal.mall.http.BaseSubscriber;
import com.zhongjian.technologycal.mall.http.ExceptionHandle;
import com.zhongjian.technologycal.mall.http.MyApiService;
import com.zhongjian.technologycal.mall.http.RetrofitClient;
import com.zhongjian.technologycal.mall.net.ApiRetrofitClient;
import com.zhongjian.technologycal.mall.utils.AppTools;
import com.zhongjian.technologycal.mall.utils.GlideCacheUtil;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/11/16.
 * 系统设置
 */

public class SettingsActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    private String username;
    @BindView(R.id.system_tv_setting_version)
    TextView system_tv_setting_version;
    @BindView(R.id.system_ll_setting_version)
    LinearLayout system_ll_setting_version;
    @BindView(R.id.system_ll_setting_status)
    ImageView system_ll_setting_status;
    @BindView(R.id.system_tv_setting_size)
    TextView system_tv_setting_size;
    private Dialog hintDialog = null;
    private MaterialDialog materialDialog = null;

    @Override
    protected void beforeInit() {
        super.beforeInit();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
//        StatusBarUtil.setColor(this, getResources().getColor(R.color.border_color), 0);
        tv_main_title.setText("设置");
        username = getIntent().getStringExtra("username");
        system_tv_setting_version.setText("" + AppTools.getVersionName(getBaseContext()));
        system_tv_setting_size.setText(GlideCacheUtil.getInstance().getCacheSize(getBaseContext()));
        initRequestVersion1();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_settings;
    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    @OnClick({R.id.system_ll_setting_pay_password,R.id.system_ll_setting_change_password,R.id.system_ll_setting_address,
            R.id.system_ll_setting_login_password,R.id.system_ll_setting_version,R.id.system_ll_setting_about,
            R.id.btn_login_out})
    public void onClickSystemPayPassword(View view) {
        Intent intent = new Intent();
        switch (view.getId()){
            /**
             * 设置支付密码
             */
            case R.id.system_ll_setting_pay_password:
                intent.setClass(getBaseContext(), SettingPayPasswordActivity.class);
                intent.putExtra("username", username);
                startActivity(intent);
                break;
            /**
             * 修改密码
             */
            case R.id.system_ll_setting_change_password:
                intent.setClass(getBaseContext(), ChangePasswordActivity.class);
                startActivity(intent);
                break;
            /**
             * 地址管理
             */
            case R.id.system_ll_setting_address:
                intent.setClass(getBaseContext(), NewsAddressListManageActivity.class);
                startActivity(intent);
                break;
            /**
             * 设置登录密码
             */
            case R.id.system_ll_setting_login_password:
                intent.setClass(getBaseContext(), SettingPasswordActivity.class);
                startActivity(intent);
                break;
            /**
             * 检查是否有新版本
             */
            case R.id.system_ll_setting_version:
                initRequestVersion();
                break;
            /**
             * 关于我们
             */
            case R.id.system_ll_setting_about:
                intent.setClass(getBaseContext(), WebViewMarkActivity.class);
                intent.putExtra("url", BaseContacts.URL_ABOUT_OUS);
                startActivity(intent);
                break;
            /**
             * 退出登录
             */
            case R.id.btn_login_out:
                materialDialog = new MaterialDialog(SettingsActivity.this)
                        .setTitle("退出确认")
                        .setMessage("确定退出登录吗？")
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                initViewRequestLoginOut();
                                materialDialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                materialDialog.dismiss();
                            }
                        });
                materialDialog.setCanceledOnTouchOutside(true);
                materialDialog.show();
                break;

        }

    }

    @Override
    public void initPresenter() {

    }
    private void initViewRequestLoginOut() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        UserUtils.clear(getBaseContext());
        MyApiService service = RetrofitClient.getInstance(SettingsActivity.this).create(MyApiService.class);
        Map<String, String> maps = new HashMap<String, String>();
        maps.put("token", UserUtils.getUserToken());
        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));

        RetrofitClient.getInstance(SettingsActivity.this).createBaseApi().execute(
                service.jsonLoginOut(body), new BaseSubscriber<LoginBean>(SettingsActivity.this) {
                    @Override
                    public void onStart() {
                        super.onStart();
                        finish();
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        if (loginBean.getError_code() == 0) {
                            ToastUitl.showShort(loginBean.getError_message());
                        } else {
                            ToastUitl.showShort(loginBean.getError_message());
                        }

                    }
                });
    }


    /**
     * 清楚缓存数据
     */
    @OnClick(R.id.system_ll_setting_clearCache)
    public void onClicksystem_ll_setting_clearCache() {
        materialDialog = new MaterialDialog(SettingsActivity.this)
                .setMessage("确定清除缓存数据吗？")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        GlideCacheUtil.getInstance().clearImageAllCache(getBaseContext());
                        system_tv_setting_size.setText("0KB");
                        ToastUitl.showShort("已清除缓存数据～");
                        materialDialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        materialDialog.dismiss();
                    }
                });
        materialDialog.setCanceledOnTouchOutside(true);
        materialDialog.show();
    }

    /**
     * 检查版本号
     */
    private void initRequestVersion() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string
                    .no_net);
            return;
        }
        ApiRetrofitClient.getInstance(getBaseContext())
                .getUrlRequestVersion(AppTools.getVersionName(getBaseContext()), new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(SettingsActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                system_ll_setting_status.setVisibility(View.GONE);
                                ToastUitl.showShort("" + baseBean.getData());
                            } else if (baseBean.getError_code() == -1) {
                                system_ll_setting_status.setVisibility(View.VISIBLE);
                                materialDialog = new MaterialDialog(SettingsActivity.this)
                                        .setMessage(R.string.app_update_info)
                                        .setPositiveButton("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Intent intent = new Intent();
                                                intent.setAction("android.intent.action.VIEW");
                                                Uri content_url = Uri.parse(BaseContacts.URL_MINE_DONWLOADING_APP);
                                                intent.setData(content_url);
                                                startActivity(intent);
                                                materialDialog.dismiss();
                                            }
                                        });
                                materialDialog.setCanceledOnTouchOutside(false);
                                materialDialog.show();
                            } else if(baseBean.getError_code() == 1){
                                system_ll_setting_status.setVisibility(View.VISIBLE);
                                materialDialog = new MaterialDialog(SettingsActivity.this)
                                        .setMessage(R.string.app_update_info)
                                        .setPositiveButton("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Intent intent = new Intent();
                                                intent.setAction("android.intent.action.VIEW");
                                                Uri content_url = Uri.parse(BaseContacts.URL_MINE_DONWLOADING_APP);
                                                intent.setData(content_url);
                                                startActivity(intent);
                                                materialDialog.dismiss();
                                            }
                                        })
                                        .setNegativeButton("取消", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                materialDialog.dismiss();
                                            }
                                        });
                                materialDialog.setCanceledOnTouchOutside(true);
                                materialDialog.show();
                            }else{
                                ToastUitl.showShort(baseBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });


    }

    /**
     * 检查版本号
     */
    private void initRequestVersion1() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string
                    .no_net);
            return;
        }
        ApiRetrofitClient.getInstance(getBaseContext())
                .getUrlRequestVersion(AppTools.getVersionName(getBaseContext()), new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(SettingsActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                system_ll_setting_status.setVisibility(View.GONE);
//                                ToastUitl.showShort("" + baseBean.getData());
                            } else if (baseBean.getError_code() == -1) {
//                                system_ll_setting_status.setVisibility(View.VISIBLE);
                            } else if(baseBean.getError_code() == 1){
                                system_ll_setting_status.setVisibility(View.VISIBLE);
                            }else{
                                ToastUitl.showShort(baseBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });


    }

}
